const express = require('express')
const path = require('path')

const app = express()
const cors = require('cors')
const joi = require('joi')


app.use(cors())
app.use(express.urlencoded({extended:false})) //解析表单

//使用express中间件来实现静态资源服务 /public/   可以访问static下的目录
app.use('/public',express.static(path.join(__dirname,'./static')))


//解析 token 中间件
const expressjwt = require('express-jwt')
const config = require('./config')
app.use(expressjwt({secret:config.jwtSecretKey}).unless({path:[/^\/my/]}))

//登录注册
const user = require('./router/user')
app.use('/my',user)

const userinfoRouter = require('./router/userinfo')
app.use('/user',userinfoRouter)



//文件上传
const uploadRouter = require('./router/upload')
app.use('/upload',uploadRouter)

//报账分类
const typeRouter = require('./router/type')
app.use('/type',typeRouter)

//报销
const reimbursementRouter = require("./router/reimbursement")
app.use('/reimbursement',reimbursementRouter)

//报销审核
const audit_controlRouter = require('./router/audit_control')
app.use('/audit_control',audit_controlRouter)

//定义错误级别中间件    
app.use((err,req,res,next)=>{
    // 表单验证失败导致的错误
    if(err instanceof joi.ValidationError){
        return res.send({
            code:500,
            message:err.details,
            data:{}
        })
    }else if(err.name === "UnauthorizedError"){
        return res.send({
            code:401,
            message:"登录信息失效请重新登录!"
        })
    }else{//未知错误
        return res.send({
            code:500,
            message:err,
            data:{}
        })
    }
})

app.listen(3000,()=>{
    console.log("服务启动成功")
})